package Snow;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class SnowJFrame extends JFrame {
    private Snow snow;
    private List<Snow> snowList;
    private Timer timer1;
    public SnowJFrame(String title){
        super(title);
        snowList=new ArrayList<Snow>();
        timer1=new Timer(100, new ActionListener() {
            int count=0;
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("count="+count);
                count++;
                if(count%10==0 && snowList.size()<=20)
                    createSnow();
                slowDown();
            }
        });
        timer1.start();
        new Thread(new Runnable(){
            int count=0;
            @Override
            public void run() {
                while(true) {
                    System.out.println("Runnable count=" + count);
                    count++;
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    if (count % 10 == 0 && snowList.size() <= 20)
                        createSnow();
                    slowDown();
                }
            }
        }).start();
    }


    /**
     * 如果不加synchronized关键字会造成空指针异常
     */
    private synchronized  void createSnow(){
        Random rd=new Random();
        //snow=new Snow(rd.nextInt(8)+2,rd.nextInt(8)-rd.nextInt(8),
        //        new ImageIcon("snow2.png"));
        ImageIcon imageIcon=new ImageIcon("snow2.jpg");
        ImageIcon imageIcon2=new ImageIcon(imageIcon.getImage().
                getScaledInstance(50, 50, Image.SCALE_DEFAULT));

        snow=new Snow(rd.nextInt(8)+2,rd.nextInt(8)-rd.nextInt(8),
               imageIcon2);
        snow.setLocation(rd.nextInt(500),0);
        snow.setSize(50,50);
        snowList.add(snow);
        this.add(snow);
    }
    private void slowDown(){
        for(Snow snow:snowList){
            snow.slowDown();
        }
    }

    public static void main(String[] args) {
        SnowJFrame snowJFrame=new SnowJFrame("雪花飘落");
        snowJFrame.setBounds(0,0,600,400);
        snowJFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        snowJFrame.setVisible(true);
    }
}
